package com.shimao.celnet.payment.service.impl;

import com.github.pagehelper.PageHelper;
import com.shimao.celnet.payment.form.PInvoiceBlueForm;
import com.shimao.celnet.payment.form.PInvoiceDetail;
import com.shimao.celnet.payment.form.PInvoiceForm;
import com.shimao.celnet.payment.mapper.PInvoiceBlueMapper;
import com.shimao.celnet.payment.model.*;
import com.shimao.celnet.payment.service.BInvoiceCompanyService;
import com.shimao.celnet.payment.service.PInvoiceBlueDetailService;
import com.shimao.celnet.payment.service.PInvoiceBlueService;
import com.shimao.celnet.payment.service.PInvoiceRedService;
import com.shimao.celnet.payment.util.FinalUtil;
import com.shimao.celnet.payment.util.MyDateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.util.*;

@Service
public class PInvoiceBlueServiceImpl extends BaseServiceImpl<PInvoiceBlue> implements PInvoiceBlueService {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired(required = false)
    private PInvoiceBlueDetailService pInvoiceBlueDetailService;

    @Autowired
    private PInvoiceRedService pInvoiceRedService;

    @Autowired
    private PInvoiceBlueService pInvoiceBlueService;
    @Autowired
    private BInvoiceCompanyService bInvoiceCompanyService;

    @Autowired
    private PInvoiceBlueMapper pInvoiceBlueMapper;

    /**
     * 页面分页查询方法
     * create by stan.ruan on 2018-01-04
     */
    @Override
    public PInvoiceBlueForm getByPage(PInvoiceBlueForm formBean, int pageNum, int length) {
        logger.info("分页查询--开始");
        //分页查询
        Example example = new Example(PInvoiceBlue.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotEmpty(formBean.getEstateSfGuid())) {
            //小区SFID
            criteria.andEqualTo("estateSfGuid", formBean.getEstateSfGuid());
        }

        if (StringUtils.isNotEmpty(formBean.getBusinessType())) {
            //业务类型：收费系统、停车系统、商城、茂家
            criteria.andEqualTo("businessType", formBean.getBusinessType());
        }

        if (StringUtils.isNotEmpty(formBean.getInvoiceTypeCode())) {
            //发票种类：004:增值税专用发票，007:增值税普通发票，026：增值税电子发票，025：增值税卷式发票
            criteria.andEqualTo("invoiceTypeCode", formBean.getInvoiceTypeCode());
        }

        if (StringUtils.isNotEmpty(formBean.getInvlidFlg())) {
            //作废标记，0代表未作废，1代表已作废
            criteria.andEqualTo("invlidFlg", formBean.getInvlidFlg());
        }

        if (StringUtils.isNotEmpty(formBean.getInvoicePrintFlg())) {
            //作废标记，0代表未打印，1代表已打印
            criteria.andEqualTo("invoicePrintFlg",formBean.getInvoicePrintFlg());

        }


        if (StringUtils.isNotEmpty(formBean.getRedFlg())) {
            //红冲标志0：未红冲；1：已红冲；默认值
            criteria.andEqualTo("redFlg", formBean.getRedFlg());
        }

        if (StringUtils.isNotEmpty(formBean.getInvoiceStatus())) {
            //开票状态：开票申请、开票成功、开票失败
            criteria.andEqualTo("invoiceStatus", formBean.getInvoiceStatus());
        }

        if (StringUtils.isNotEmpty(formBean.getSelStartTime()) && StringUtils.isNotEmpty(formBean.getSelEndTime())) {
            //开票开始日期-开票结束日期
            try {
                criteria.andBetween("invoiceStartTime", MyDateUtil.dateToStamp(formBean.getSelStartTime()),MyDateUtil.dateToStamp(formBean.getSelEndTime()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (StringUtils.isNotEmpty(formBean.getSerialNo())) {
            //开票流水号
            criteria.andLike("serialNo", "%" + formBean.getSerialNo() + "%");
        }
        if (StringUtils.isNotEmpty(formBean.getInvoiceNo())) {
            //开票流水号
            criteria.andLike("invoiceNo", "%" + formBean.getInvoiceNo() + "%");
        }
        //分页查询
        PageHelper.startPage(pageNum, length);
        List<PInvoiceBlue> tableList = getByExample(example);
        formBean.setPageInfo(tableList);
        return formBean;
    }

    /**
     * 保存发票记录以及该记录的明细
     * create by stan.ruan on 2018-01-04
     */
    @Override
    public int save(PInvoiceBlue sBean, List<PInvoiceBlueDetail> pInvoiceBlueDetailList) {
        int retCnt;
        Date date = new Date();
        String loginUserGuid = FinalUtil.INTER_FACE_USER_ID;
        sBean.setCreatedUserGuid(loginUserGuid);
        sBean.setUpdateDate(date);
        sBean.setUpdateUserGuid(loginUserGuid);
        sBean.setCreatedDate(date);
        //新增蓝票记录
        retCnt = super.save(sBean);
        //新增付款记录明细
        String invoiceGuid = sBean.getGuid();
        for (PInvoiceBlueDetail pInvoiceBlueDetail : pInvoiceBlueDetailList) {
            pInvoiceBlueDetail.setInvoiceGuid(invoiceGuid);//蓝票记录GUID
            pInvoiceBlueDetail.setCreatedUserGuid(loginUserGuid);
            pInvoiceBlueDetail.setUpdateDate(date);
            pInvoiceBlueDetail.setUpdateUserGuid(loginUserGuid);
            pInvoiceBlueDetail.setCreatedDate(date);
            //蓝票记录明细保存
            pInvoiceBlueDetailService.save(pInvoiceBlueDetail);
        }
        return retCnt;
    }


    /**
     * 通过开票guid，查询蓝票记录详情，蓝票明细，红票记录列表
     * create by stan.ruan on 2018-01-04
     */
    @Override
    public Map<String, Object> getInfo(String invoiceGuid) {
        Map<String, Object> retMap = new HashMap<>();
        //蓝票详情获取
        PInvoiceBlue blueBean = this.getByKey(invoiceGuid);
        retMap.put("pInvoiceBlue", blueBean);

        //蓝票详情的开票明细获取
        retMap.put("pInvoiceDetailList", pInvoiceBlueDetailService.getByInvoiceGuid(invoiceGuid));

        //蓝票详情对应的红冲list
        //分页查询
        Example example = new Example(PInvoiceRed.class);
        Example.Criteria criteria = example.createCriteria();
        if (blueBean == null) {
            Map<String, Object> stringObjectMap = new HashMap<String, Object>();
            stringObjectMap.put("erro", "原发票不存在！");
            return stringObjectMap;
        }
        if (StringUtils.isNotEmpty(blueBean.getInvoiceCode())) {
            //原(蓝)发票代码 invoiceCode
            criteria.andEqualTo("originalInvoiceCode", blueBean.getInvoiceCode());
        }
        if (StringUtils.isNotEmpty(blueBean.getInvoiceNo())) {
            //原(蓝)发票号码invoiceNo
            criteria.andEqualTo("originalInvoiceNo", blueBean.getInvoiceNo());
        }
        retMap.put("pInvoiceRedList", pInvoiceRedService.getByExample(example));
        return retMap;
    }

    /**
     * 通过开票guid，查询发票记录详情，发票明细
     * create by stan.ruan on 2018-01-04
     */
    @Override
    public PInvoiceForm getInvoiceForm(String invoiceGuid, String blueRedType) {
        PInvoiceForm formBean = new PInvoiceForm();
        if (StringUtils.isEmpty(blueRedType)) {
            blueRedType = FinalUtil.INVOICE_BULE;
        }

        //页面数据查询结果
        if (FinalUtil.INVOICE_BULE.equals(blueRedType)) {
            Map<String, Object> retMap = this.getInfo(invoiceGuid);
            Object obj = retMap.get("pInvoiceBlue");
            if (obj == null) {
                return formBean;
            }
            PInvoiceBlue blueBean = (PInvoiceBlue) obj;
            //根据sfid查询销方信息
            BInvoiceCompany bInvoiceCompany = bInvoiceCompanyService.getCompanyByEstateSFGuid(blueBean.getEstateSfGuid());
            //把销方信息回写到页面
            formBean.setUserName(blueBean.getUserName());
            formBean.setHouseName(blueBean.getHouseName());
            formBean.setHouseSfId(blueBean.getHouseSfId());
            if (bInvoiceCompany != null) {
                formBean.setAddressAccount(bInvoiceCompany.getAddressAccount());
                formBean.setAddressPhone(bInvoiceCompany.getAddressPhone());
                formBean.setCompanyName(bInvoiceCompany.getCompanyName());
            }
            formBean.setGuid(blueBean.getGuid());//记录 GUID
            formBean.setImmediatelyFlg(blueBean.getImmediatelyFlg());//即时开票
            formBean.setBusinessType(blueBean.getBusinessType());//支付业务类型
            formBean.setEstateSfGuid(blueBean.getEstateSfGuid());//小区SF-GUID
            formBean.setDeviceType(blueBean.getDeviceType());//设备类型
            formBean.setInvoiceTypeCode(blueBean.getInvoiceTypeCode());//发票种类编码
            formBean.setOrganizationCode(blueBean.getOrganizationCode());//组织机构代码
            formBean.setSerialNo(blueBean.getSerialNo());//开票流水号
            formBean.setInvoiceSpecialMark(blueBean.getInvoiceSpecialMark());//特殊票种标记
            formBean.setSellerTaxNo(blueBean.getSellerTaxNo());//销方单位税号
            formBean.setInvoiceYerminalCode(blueBean.getInvoiceYerminalCode());//开票点编码
            formBean.setBuyerTaxNo(blueBean.getBuyerTaxNo());//购方单位税号
            formBean.setBuyerName(blueBean.getBuyerName());//购方单位名称
            formBean.setBuyerAddressPhone(blueBean.getBuyerAddressPhone());//购方地址及电话
            formBean.setBuyerBankAccount(blueBean.getBuyerBankAccount());//购方开户行及账号
            formBean.setBuyerPhone(blueBean.getBuyerPhone());//购方电话
            formBean.setBuyerEmail(blueBean.getBuyerEmail());//购方邮箱
            formBean.setDrawer(blueBean.getDrawer());//开票人
            formBean.setChecker(blueBean.getChecker());//复核人
            formBean.setPayee(blueBean.getPayee());//收款人
            formBean.setInvoiceListMark(blueBean.getInvoiceListMark());//清单标志
            formBean.setRedInfoNo(blueBean.getRedInfoNo());//红字信息表编号
            formBean.setTaxationMode(blueBean.getTaxationMode());//征税方式
            formBean.setDeductibleAmount(blueBean.getDeductibleAmount());//扣除额

                if (StringUtils.isNotEmpty(blueBean.getInvoiceTotalPrice())) {
                    formBean.setInvoiceTotalPrice(MyDateUtil.getTxFloat(blueBean.getInvoiceTotalPrice()));//合计金额
                    System.out.println("@@@@@@@@@@@@@@@@@@@@@@@"+String.valueOf(Double.valueOf(MyDateUtil.getTxFloat(blueBean.getInvoiceTotalPrice())) ));
                }
                if (StringUtils.isNotEmpty(blueBean.getInvoiceTotalTax())) {
                    formBean.setInvoiceTotalTax(MyDateUtil.getTxFloat(blueBean.getInvoiceTotalTax()));//合计税额
                    System.out.println("@@@@@@@@@@@@@@@@@@@@@@@"+String.valueOf(Double.valueOf(MyDateUtil.getTxFloat(blueBean.getInvoiceTotalTax()))));
                }

                if (StringUtils.isNotEmpty(blueBean.getInvoiceTotalPriceTax())) {
                    formBean.setInvoiceTotalPriceTax(MyDateUtil.getTxFloat(blueBean.getInvoiceTotalPriceTax()));//蓝票-价税合计（开蓝票金额）
                    System.out.println("@@@@@@@@@@@@@@@@@@@@@@"+String.valueOf((Double.valueOf(MyDateUtil.getTxFloat(blueBean.getInvoiceTotalPriceTax()))) / 100.0));
                    formBean.setInvoiceTotalPriceTaxRMB(MyDateUtil.getRMB(blueBean.getInvoiceTotalPriceTax()));
                }
                formBean.setInvlidFlg(blueBean.getInvlidFlg());//作废标志
                formBean.setInvlidTime(blueBean.getInvlidTime());//作废时间
                formBean.setRedFlg(blueBean.getRedFlg());//红冲标志
                formBean.setRedInvoiceTotalPriceTax(blueBean.getRedInvoiceTotalPriceTax());//红冲-价税合计（开红票金额）
                formBean.setEnRedAmount(blueBean.getEnRedAmount());//可红冲金额合计；
                formBean.setSignatureParameter(blueBean.getSignatureParameter());//签名值参数
                formBean.setTaxDiskNo(blueBean.getTaxDiskNo());//税控盘编号
                formBean.setTaxDiskKey(blueBean.getTaxDiskKey());//税控盘口令
                formBean.setTaxDiskPassword(blueBean.getTaxDiskPassword());//税务数字证书密码
//        formBean.setGoodsCodeVersion(blueBean.getGoodsCodeVersion());//商品编码版本号
//        formBean.setConsolidatedTaxRate(blueBean.getConsolidatedTaxRate());//综合税率
//        formBean.setnotificationNo(blueBean.getnotificationNo());//通知单编号

                formBean.setRemarks((blueBean.getHouseName() == null ? "" : blueBean.getHouseName()) + " " +(blueBean.getRemarks() == null ? "" : blueBean.getRemarks()));//备注 月份 + 房间id
                formBean.setInvoiceCode(blueBean.getInvoiceCode());//发票代码
                formBean.setInvoiceNo(blueBean.getInvoiceNo());//发票号码
                formBean.setInvoiceStartTime(blueBean.getInvoiceStartTime());//开票开始时间
                formBean.setInvoiceEndTime(blueBean.getInvoiceEndTime());//开票完成时间
                formBean.setTaxControlCode(blueBean.getTaxControlCode());//税控码
                formBean.setInvoiceCheckCode(blueBean.getInvoiceCheckCode());//校验码
                formBean.setInvoiceQrcode(blueBean.getInvoiceQrcode());//二维码
                formBean.setInvoicePrintType(blueBean.getInvoicePrintType());//打印类型
//        formBean.setInvoicePrintMode(blueBean.getInvoicePrintMode());//打印方式
                formBean.setInvoicePrintTime(blueBean.getInvoicePrintTime());//打印日期
                formBean.setInvoicePrintFlg(blueBean.getInvoicePrintFlg());//打印标志
                formBean.setInvoiceStatus(blueBean.getInvoiceStatus());//开票状态
                formBean.setAppKey(blueBean.getAppKey());//应用key
                formBean.setInterfaceId(blueBean.getInterfaceId());//接口编号
                formBean.setInvoiceUrl(blueBean.getInvoiceUrl());//电子发票下载地址
                formBean.setInvoicetype(FinalUtil.INVOICE_BULE);
                //2、蓝票详情的开票明细
                List<PInvoiceBlueDetail> blueDetailList = (List<PInvoiceBlueDetail>) retMap.get("pInvoiceDetailList");
//            formBean.setpInvoiceDetails(blueDetailList);
                List<PInvoiceDetail> bDetails = new ArrayList<PInvoiceDetail>();
                for (PInvoiceBlueDetail detailBean : blueDetailList) {
                    PInvoiceDetail bBean = new PInvoiceDetail();
                    bBean.setGoodsLineNo(detailBean.getGoodsLineNo());//明细行号
                    bBean.setExsysDetailId(detailBean.getExsysDetailId());//外部系统明细id
                    bBean.setGoodsLineNature(detailBean.getGoodsLineNature());//发票行性质
                    bBean.setGoodsCode(detailBean.getGoodsCode());//商品编码
                    bBean.setGoodsTaxItem(detailBean.getGoodsTaxItem());//商品税目
                    bBean.setGoodsExtendCode(detailBean.getGoodsExtendCode());//自行编码
                    bBean.setGoodsName(detailBean.getGoodsName());//商品名称
                    bBean.setGoodsSpecification(detailBean.getGoodsSpecification());//规格型号
                    bBean.setGoodsUnit(detailBean.getGoodsUnit());//计量单位
                    bBean.setGoodsQuantity(detailBean.getGoodsQuantity());//商品数量
                    if (!("".equals(detailBean.getGoodsPrice()) || detailBean.getGoodsPrice() == null)) {
                        bBean.setGoodsPrice(MyDateUtil.getTxFloat(detailBean.getGoodsPrice()));//商品单价
                        System.out.println(MyDateUtil.getTxFloat(detailBean.getGoodsPrice()));
                        bBean.setGoodsTotalPrice(MyDateUtil.getTxFloat(detailBean.getGoodsTotalPrice()));//金额
                        System.out.println(String.valueOf(detailBean.getGoodsTotalPrice()));
                    }
                    bBean.setGoodsTotalTax(String.format("%.2f", (Float.valueOf(detailBean.getGoodsTotalPrice()) * Float.valueOf(detailBean.getGoodsTaxRate()) / (1.0 + Float.valueOf(detailBean.getGoodsTaxRate()))) / 100.0));//税额=商品总金额（含税）*商品税率/（1+税率）
                    System.out.println("=============>>>>"+ (Double.valueOf(detailBean.getGoodsTotalPrice()) * Double.valueOf(detailBean.getGoodsTaxRate()) / (1.0 + Double.valueOf(detailBean.getGoodsTaxRate())))/100 );
                    bBean.setGoodsTaxRate(detailBean.getGoodsTaxRate());//税率
                    bBean.setPriceTaxMark(detailBean.getPriceTaxMark());//含税标志
                    bBean.setGoodsDiscountLineNo(detailBean.getGoodsDiscountLineNo());//折行对应行号
                    bBean.setVatSpecialManagement(detailBean.getVatSpecialManagement());//增值税特殊管理
                    bBean.setFreeTaxMark(detailBean.getFreeTaxMark());//零税率标识
                    bBean.setPreferential(detailBean.getPreferential());//是否使用优惠政策
                    bBean.setPaymentDate(detailBean.getPaymentDate());//缴费完成日期
                    bDetails.add(bBean);
                }
                formBean.setpInvoiceDetails(bDetails);
        } else if (FinalUtil.INVOICE_RED.equals(blueRedType)) {
            //红票
            Map<String, Object> retMap = pInvoiceRedService.getInfo(invoiceGuid);
            Object obj = retMap.get("pInvoiceRed");
            if (obj == null) {
                return formBean;
            }
            PInvoiceRed redBean = (PInvoiceRed) obj;
            BInvoiceCompany bInvoiceCompany = bInvoiceCompanyService.getCompanyByEstateSFGuid(redBean.getEstateSfGuid());
            //把销方信息回写到页面
            formBean.setUserName(redBean.getUserName());
            formBean.setHouseName(redBean.getHouseName());
            formBean.setHouseSfId(redBean.getHouseSfId());
            if (bInvoiceCompany != null) {
                formBean.setAddressAccount(bInvoiceCompany.getAddressAccount());
                formBean.setAddressPhone(bInvoiceCompany.getAddressPhone());
                formBean.setCompanyName(bInvoiceCompany.getCompanyName());
            }
            formBean.setGuid(redBean.getGuid());//记录 GUID
//            formBean.setImmediatelyFlg(redBean.getImmediatelyFlg());//即时开票
            formBean.setBusinessType(redBean.getBusinessType());//支付业务类型
            formBean.setEstateSfGuid(redBean.getEstateSfGuid());//小区SF-GUID
            formBean.setDeviceType(redBean.getDeviceType());//设备类型
            formBean.setInvoiceTypeCode(redBean.getInvoiceTypeCode());//发票种类编码
            formBean.setOrganizationCode(redBean.getOrganizationCode());//组织机构代码
            formBean.setSerialNo(redBean.getSerialNo());//开票流水号
            formBean.setInvoiceSpecialMark(redBean.getInvoiceSpecialMark());//特殊票种标记
            formBean.setSellerTaxNo(redBean.getSellerTaxNo());//销方单位税号
            formBean.setInvoiceYerminalCode(redBean.getInvoiceYerminalCode());//开票点编码
            formBean.setBuyerTaxNo(redBean.getBuyerTaxNo());//购方单位税号
            formBean.setBuyerName(redBean.getBuyerName());//购方单位名称
            formBean.setBuyerAddressPhone(redBean.getBuyerAddressPhone());//购方地址及电话
            formBean.setBuyerBankAccount(redBean.getBuyerBankAccount());//购方开户行及账号
            formBean.setBuyerPhone(redBean.getBuyerPhone());//购方电话
            formBean.setBuyerEmail(redBean.getBuyerEmail());//购方邮箱
            formBean.setDrawer(redBean.getDrawer());//开票人
            formBean.setChecker(redBean.getChecker());//复核人
            formBean.setPayee(redBean.getPayee());//收款人
            formBean.setInvoiceListMark(redBean.getInvoiceListMark());//清单标志
            formBean.setRedInfoNo(redBean.getRedInfoNo());//红字信息表编号
            formBean.setTaxationMode(redBean.getTaxationMode());//征税方式
            formBean.setDeductibleAmount(redBean.getDeductibleAmount());//扣除额
            if (StringUtils.isNotEmpty(redBean.getInvoiceTotalPrice())) {
                //formBean.setInvoiceTotalPrice(String.valueOf(-Math.abs(Float.valueOf(redBean.getInvoiceTotalPrice())) / 100.0));//合计金额
                formBean.setInvoiceTotalPrice(String.valueOf(Float.valueOf(redBean.getInvoiceTotalPrice()) / 100.0));//合计金额
            }
            // formBean.setInvoiceTotalPrice(redBean.getInvoiceTotalPrice());//合计金额
            if (StringUtils.isNotEmpty(redBean.getInvoiceTotalTax())) {
                //formBean.setInvoiceTotalTax(String.valueOf(-Math.abs(Float.valueOf(redBean.getInvoiceTotalTax())) / 100.0));//合计金额
                formBean.setInvoiceTotalTax(String.valueOf(Float.valueOf(redBean.getInvoiceTotalTax()) / 100.0));//合计金额

            }
            // formBean.setInvoiceTotalTax(redBean.getInvoiceTotalTax());//合计税额
            if (StringUtils.isNotEmpty(redBean.getInvoiceTotalPriceTax())) {
               // formBean.setInvoiceTotalPriceTax(String.valueOf(-Math.abs((Float.valueOf(redBean.getInvoiceTotalPriceTax())) / 100.0)));//合计金额
                formBean.setInvoiceTotalPriceTax(String.valueOf((Float.valueOf(redBean.getInvoiceTotalPriceTax()) / 100.0)));//合计金额
            }
            formBean.setInvoiceTotalPriceTaxRMB("(负数)"+MyDateUtil.getRMB(String.valueOf(Math.abs(Integer.valueOf(redBean.getInvoiceTotalPriceTax())))));
            //  formBean.setInvoiceTotalPriceTax(redBean.getInvoiceTotalPriceTax());//蓝票-价税合计（开蓝票金额）
            formBean.setInvlidFlg(redBean.getInvlidFlg());//作废标志
            formBean.setInvlidTime(redBean.getInvlidTime());//作废时间
//            formBean.setRedFlg(redBean.getRedFlg());//红冲标志
//            formBean.setRedInvoiceTotalPriceTax(redBean.getRedInvoiceTotalPriceTax());//红冲-价税合计（开红票金额）
//            formBean.setEnRedAmount(redBean.getEnRedAmount());//可红冲金额合计；
            formBean.setSignatureParameter(redBean.getSignatureParameter());//签名值参数
            formBean.setTaxDiskNo(redBean.getTaxDiskNo());//税控盘编号
            formBean.setTaxDiskKey(redBean.getTaxDiskKey());//税控盘口令
            formBean.setTaxDiskPassword(redBean.getTaxDiskPassword());//税务数字证书密码
//        formBean.setGoodsCodeVersion(blueBean.getGoodsCodeVersion());//商品编码版本号
//        formBean.setConsolidatedTaxRate(blueBean.getConsolidatedTaxRate());//综合税率
//        formBean.setnotificationNo(blueBean.getnotificationNo());//通知单编号
            formBean.setInvoicetype(FinalUtil.INVOICE_RED);
            formBean.setRemarks((redBean.getHouseName() == null ? "" : redBean.getHouseName() )+ " " + (redBean.getRemarks() == null ? "" : redBean.getRemarks()));//备注 月份 + 房间id
            formBean.setInvoiceCode(redBean.getInvoiceCode());//发票代码
            formBean.setInvoiceNo(redBean.getInvoiceNo());//发票号码
            formBean.setInvoiceStartTime(redBean.getInvoiceStartTime());//开票开始时间
            formBean.setInvoiceEndTime(redBean.getInvoiceEndTime());//开票完成时间
            formBean.setTaxControlCode(redBean.getTaxControlCode());//税控码
            formBean.setInvoiceCheckCode(redBean.getInvoiceCheckCode());//校验码
            formBean.setInvoiceQrcode(redBean.getInvoiceQrcode());//二维码
            formBean.setInvoicePrintType(redBean.getInvoicePrintType());//打印类型
//        formBean.setInvoicePrintMode(blueBean.getInvoicePrintMode());//打印方式
            formBean.setInvoicePrintTime(redBean.getInvoicePrintTime());//打印日期
            formBean.setInvoicePrintFlg(redBean.getInvoicePrintFlg());//打印标志
            formBean.setInvoiceStatus(redBean.getInvoiceStatus());//开票状态
            formBean.setAppKey(redBean.getAppKey());//应用key
            formBean.setInterfaceId(redBean.getInterfaceId());//接口编号
            formBean.setInvoiceUrl(redBean.getInvoiceUrl());//电子发票下载地址

            //2、红票详情的开票明细
            List<PInvoiceRedDetail> redDetails = (List<PInvoiceRedDetail>) retMap.get("pInvoiceDetailList");
            List<PInvoiceDetail> bDetails = new ArrayList<PInvoiceDetail>();
            for (PInvoiceRedDetail detailBean : redDetails) {
                PInvoiceDetail bBean = new PInvoiceDetail();
                bBean.setGoodsLineNo(detailBean.getGoodsLineNo());//明细行号
                bBean.setExsysDetailId(detailBean.getExsysDetailId());//外部系统明细id
                bBean.setGoodsLineNature(detailBean.getGoodsLineNature());//发票行性质
                bBean.setGoodsCode(detailBean.getGoodsCode());//商品编码
                bBean.setGoodsTaxItem(detailBean.getGoodsTaxItem());//商品税目
                bBean.setGoodsExtendCode(detailBean.getGoodsExtendCode());//自行编码
                bBean.setGoodsName(detailBean.getGoodsName());//商品名称
                bBean.setGoodsSpecification(detailBean.getGoodsSpecification());//规格型号
                bBean.setGoodsUnit(detailBean.getGoodsUnit());//计量单位
                bBean.setGoodsQuantity(String.valueOf(-Integer.valueOf(detailBean.getGoodsQuantity())));//商品数量
                if (StringUtils.isNotEmpty(detailBean.getGoodsPrice())) {
                    bBean.setGoodsPrice(String.valueOf(Float.valueOf(detailBean.getGoodsPrice()) / 100.0));//单价
                }
                //bBean.setGoodsPrice(detailBean.getGoodsPrice());//商品单价
                if (StringUtils.isNotEmpty(detailBean.getGoodsTotalPrice())) {
                    bBean.setGoodsTotalPrice(String.valueOf(-Float.valueOf(detailBean.getGoodsTotalPrice()) / 100.0));//合计金额
                }
                //  bBean.setGoodsTotalPrice(detailBean.getGoodsTotalPrice());//金额
                bBean.setGoodsTotalTax(String.format("%.2f", (-Float.valueOf(detailBean.getGoodsTotalPrice()) * Float.valueOf(detailBean.getGoodsTaxRate()) / (1.0 + Float.valueOf(detailBean.getGoodsTaxRate()))) / 100.0));//税额
                bBean.setGoodsTaxRate(detailBean.getGoodsTaxRate());//税率
                bBean.setPriceTaxMark(detailBean.getPriceTaxMark());//含税标志
                bBean.setGoodsDiscountLineNo(detailBean.getGoodsDiscountLineNo());//折行对应行号
                bBean.setVatSpecialManagement(detailBean.getVatSpecialManagement());//增值税特殊管理
                bBean.setFreeTaxMark(detailBean.getFreeTaxMark());//零税率标识
                bBean.setPreferential(detailBean.getPreferential());//是否使用优惠政策
                bBean.setPaymentDate(detailBean.getPaymentDate());//缴费完成日期

                bDetails.add(bBean);
            }
            formBean.setpInvoiceDetails(bDetails);
        }
        return formBean;
    }

    @Override
    public List<PInvoiceBlue> invoiceList() {
        //当前时间
        String nowDate = MyDateUtil.getCurrentStrDate();
        //当前时间一小时前
        String beforeDate = MyDateUtil.getPreOneDayYmdhms();

        return pInvoiceBlueMapper.invoiceList(beforeDate,nowDate);

    }

    @Override
    public List<PInvoiceBlue> EinvoiceList() {
        String startTime = "2018-09-17 10:00:00";
        String endTime = "2018-09-17 16:00:00";
        return pInvoiceBlueMapper.EinvoiceList(startTime,endTime);
        //return null;
    }

    @Override
    public String getGuidByInvoiceNo(String invoiceNo) {
        return pInvoiceBlueMapper.getGuidByInvoiceNo(invoiceNo);
    }

    /**
     * 通过开票parent_guid和originalInvoiceNo，查询蓝票记录以及蓝票记录明细
     */
    @Override
    public Map<String, Object> getInfoRed(String blueReceiptGuid, String originalInvoiceNo) {
        Map<String, Object> retMap = new HashMap<>();
        Example exampleblue = new Example(PInvoiceBlue.class);
        Example.Criteria criteriablue = exampleblue.createCriteria();
        criteriablue.andEqualTo("guid",blueReceiptGuid);
        criteriablue.andEqualTo("invoiceNo",originalInvoiceNo);
        //蓝票详情获取
        PInvoiceBlue blueBean = pInvoiceBlueService.getByExample(exampleblue).get(0);
        retMap.put("pInvoiceBlue", blueBean);

        //蓝票详情的开票明细获取
        retMap.put("pInvoiceDetailList", pInvoiceBlueDetailService.getByInvoiceGuid(blueBean.getGuid()));
        //蓝票详情对应的红冲list
       //分页
        Example  example = new Example(PInvoiceRed.class);
        Example.Criteria criteria = example.createCriteria();
        if (blueBean == null) {
            Map<String, Object> stringObjectMap = new HashMap<String, Object>();
            stringObjectMap.put("erro", "原发票不存在！");
            return stringObjectMap;
        }
        if (StringUtils.isNotEmpty(blueBean.getInvoiceCode())) {
            //原(蓝)发票代码 invoiceCode
            criteria.andEqualTo("originalInvoiceCode", blueBean.getInvoiceCode());
        }
        if (StringUtils.isNotEmpty(blueBean.getInvoiceNo())) {
            //原(蓝)发票号码invoiceNo
            criteria.andEqualTo("originalInvoiceNo", blueBean.getInvoiceNo());
        }
        retMap.put("pInvoiceRedList", pInvoiceRedService.getByExample(example));
        return retMap;
    }

    /**
     * 通过发票号查询发票
     */
    @Override
    public PInvoiceBlue getInvoiceByinvoiceNo(String invoiceNo) {

        return pInvoiceBlueMapper.getInvoiceByinvoiceNo(invoiceNo);
    }

    /**
     * 通过流水号查询发票
     */
    @Override
    public PInvoiceBlue getInvoiceBySerialNo(String serial_no) {

        return pInvoiceBlueMapper.getInvoiceBySerialNo(serial_no);
    }

    /**
     * 通过开票终端查询发票
     */
    @Override
    public PInvoiceBlue getInvoiceByInvoiceYerminalCode(String invoiceYerminalCode) {
        Example exampleblue = new Example(PInvoiceBlue.class);
        Example.Criteria criteriablue = exampleblue.createCriteria();
        criteriablue.andEqualTo("invoiceYerminalCode",invoiceYerminalCode);
        criteriablue.andIsNotNull("invoiceNo");
        criteriablue.andIsNotNull("invoiceCode");
        criteriablue.andIsNotNull("invoiceCheckCode");
        criteriablue.andIsNotNull("invoiceQrcode");
        //蓝票详情获取
        PInvoiceBlue blueBean = pInvoiceBlueService.getByExample(exampleblue).get(0);
        return blueBean;
    }
}
